//
//  InstallationListTableViewCell.swift
//  ezyform
//
//  Created by MoennigQ on 24/2/19.
//  Copyright © 2019 Client.Solution Pty Ltd. All rights reserved.
//
import UIKit
import SnapKit
class InstallationListTableViewCell: TableViewCell {
    //MARK: - 详情
    var dateView: PVDsListCellCalendarView!
    var gwdIDLabel: ContentLabel!
    var nameLabel: ContentLabel!
    var addresslabel: ContentLabel!
    var schedulerTimelabel: ContentLabel!
    var assignedByLabel: PaddingLabel!
    var installationTypeLabel: PaddingLabel!
    var powerLabel: PaddingLabel!
    var pickUpRequired: PaddingLabel!
    var jobStatusView: JobsListStatusView!
    var jobTypeImageView: UIImageView!
    //MARK: - 没有全部完成时的view
    let backView = UIView()
    
    var barcodeBtn: PVDsListCellOperButton!
    var checklistBtn: PVDsListCellOperButton!
    var signatureBtn: PVDsListCellOperButton!
    //MARK: - 全部完成时的只显示all done
    var allDoneImageView: UIImageView!
    
    override func setUpviews(){
        self.selectionStyle = .none//取消选中效果
        //设置透明颜色
        self.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.contentView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        //back view
        let backView = CustomBackView()
        backView.backgroundColor = .white
        self.contentView.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview().offset(-16)
        }
        //date view
        dateView = PVDsListCellCalendarView()
        backView.addSubview(dateView)
        dateView.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(Constant.AllOutMargin)
            make.width.height.greaterThanOrEqualTo(0)
            make.width.equalTo(dateView.snp.height)//高宽相当
        }
        //gwt id
        gwdIDLabel = ContentLabel(R.font.interMedium(size: 15))
        backView.addSubview(gwdIDLabel)
        gwdIDLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-Constant.AllOutMargin)
            make.centerY.equalTo(dateView)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //job type image view
        jobTypeImageView = UIImageView()
        backView.addSubview(jobTypeImageView)
        jobTypeImageView.snp.makeConstraints { (make) in
            make.right.equalTo(gwdIDLabel.snp.left).offset(-3)
            make.centerY.equalTo(dateView)
            make.width.height.equalTo(20)
        }
        //name
        nameLabel = ContentLabel(R.font.interBold(size: 18), hexStr: "#101E30FF")
        nameLabel.numberOfLines = 0
        backView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(dateView.snp.bottom).offset(18)
            make.left.equalTo(dateView)
            make.width.height.greaterThanOrEqualTo(0)
            
        }
        //
        //job status view
        jobStatusView = JobsListStatusView()
        jobStatusView.setContentHuggingPriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        jobStatusView.setContentCompressionResistancePriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        backView.addSubview(jobStatusView)
        jobStatusView.snp.makeConstraints { (make) in
            make.centerY.equalTo(nameLabel)
            make.left.equalTo(nameLabel.snp.right)
            make.right.equalTo(gwdIDLabel)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //address
        addresslabel = ContentLabel()
        addresslabel.textAlignment = .left
        addresslabel.numberOfLines = 0
        backView.addSubview(addresslabel)
        addresslabel.snp.makeConstraints { (make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(10)
            make.left.equalTo(dateView)
            make.right.equalTo(gwdIDLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        schedulerTimelabel = ContentLabel(R.font.interRegular(size: 13),hexStr: "#292D32B2")
        schedulerTimelabel.textAlignment = .left
        schedulerTimelabel.numberOfLines = 0
        backView.addSubview(schedulerTimelabel)
        schedulerTimelabel.snp.makeConstraints { (make) in
            make.top.equalTo(addresslabel.snp.bottom).offset(8)
            make.left.equalTo(dateView)
            make.right.equalTo(gwdIDLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //assigned by
        assignedByLabel = PaddingLabel()
        assignedByLabel.setFont(R.font.interRegular(size: 14))
        assignedByLabel.textColor = UIColor(hexStr: "#292D32B2")
        assignedByLabel.backgroundColor = UIColor(hexStr: "#005D2D0F")
        assignedByLabel.layer.cornerRadius = Constant.StandardCornerRadius
        assignedByLabel.clipsToBounds = true
        assignedByLabel.textAlignment = .left
        assignedByLabel.numberOfLines = 0
        backView.addSubview(assignedByLabel)
        assignedByLabel.snp.makeConstraints { (make) in
            make.top.equalTo(schedulerTimelabel.snp.bottom).offset(12)
            make.left.right.equalTo(addresslabel)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //installationTypeLabel
        installationTypeLabel = PaddingLabel()
        installationTypeLabel.adjustsFontForContentSizeCategory = true
        installationTypeLabel.textColor = .white
        installationTypeLabel.setFont(R.font.interMedium(size: 12))
        installationTypeLabel.backgroundColor = UIColor(hexStr: "#688F4E")
        installationTypeLabel.layer.cornerRadius = Constant.StandardCornerRadius
        installationTypeLabel.clipsToBounds = true
        installationTypeLabel.numberOfLines = 0
        backView.addSubview(installationTypeLabel)
        installationTypeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(addresslabel)
            make.top.equalTo(assignedByLabel.snp.bottom).offset(12)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //powerLabel
        powerLabel = ViewFactory.shared.generateLabelWithBorder(textHexStr: "#70798A")
        backView.addSubview(powerLabel)
        powerLabel.snp.makeConstraints { (make) in
            make.left.equalTo(installationTypeLabel.snp.right).offset(Constant.InternalMargin)
            make.centerY.height.equalTo(installationTypeLabel)
            make.width.greaterThanOrEqualTo(0)
        }
        //pickUpRequired
        pickUpRequired = ViewFactory.shared.generateLabelWithBorder(textHexStr: "#70798A")
        backView.addSubview(pickUpRequired)
        pickUpRequired.snp.makeConstraints { (make) in
            make.left.equalTo(powerLabel.snp.right).offset(Constant.InternalMargin)
            make.centerY.height.equalTo(installationTypeLabel)
            make.width.greaterThanOrEqualTo(0)
        }
        //line view
        let lineView = View(hexStr: Constant.SeparatorColorHexStr)
        backView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.equalTo(pickUpRequired.snp.bottom).offset(10)
            make.left.right.equalTo(addresslabel)
            make.height.equalTo(1)
        }
        //*******bottom buttons
        //全部完成时，显示all done，back view隐藏
        let bottomBtnSize = self.getOperateBtnSize()
        allDoneImageView = UIImageView(image: R.image.installation_list_cell_alldone())
        allDoneImageView.contentMode = .scaleAspectFit
        backView.addSubview(allDoneImageView)
        allDoneImageView.snp.makeConstraints { make in
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(bottomBtnSize.height)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-20)
        }
        //1.barcode
        barcodeBtn = PVDsListCellOperButton()
        backView.addSubview(barcodeBtn)
        barcodeBtn.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.left.equalTo(addresslabel)
            make.size.equalTo(bottomBtnSize)
            make.bottom.equalTo(-20)
        }
        //2.checklist
        checklistBtn = PVDsListCellOperButton()
        backView.addSubview(checklistBtn)
        checklistBtn.snp.makeConstraints { make in
            make.left.equalTo(barcodeBtn.snp.right).offset(internalBetweenBtns)
            make.top.size.equalTo(barcodeBtn)
        }
        //3.signature
        signatureBtn = PVDsListCellOperButton()
        backView.addSubview(signatureBtn)
        signatureBtn.snp.makeConstraints { make in
            make.left.equalTo(checklistBtn.snp.right).offset(internalBetweenBtns)
            make.top.size.equalTo(barcodeBtn)
        }
    }
    //MARK: - 底部区域按钮
    let internalBetweenBtns: CGFloat = 10
    private func getOperateBtnSize()->CGSize{
        //bottom button左右两边的间隔
        let leftRightMargin: CGFloat = 28
        //btn间的间隔
        let btnCnt: CGFloat = 3
        //
        let backViewWidth: CGFloat = APPConfig.WidthForPortrait - leftRightMargin * 2
        let btnWidth = (backViewWidth - internalBetweenBtns * 3) / btnCnt
        if btnWidth < 70 {//小于70，高度30
            return CGSize(width: btnWidth, height: 20)
        }else if btnWidth < 100 && btnWidth >= 70 {//小于100，高度30
            return CGSize(width: btnWidth, height: 30)
        }else{
            return CGSize(width: 100, height: 40)
        }
        
    }
    func setData(_ model: InstallationListModel){
        
        let monthStr = DateUtil().convertDateStrToDateStr(dateStr: model.install_date, oldFormat: "MMM dd yyyy", newFormat: "MMM")
        
        let dayStr = DateUtil().convertDateStrToDateStr(dateStr: model.install_date, oldFormat: "MMM dd yyyy", newFormat: "dd")
        self.dateView.setData(monthStr,day: dayStr)
        
        self.gwdIDLabel.text = model.gwt_id
        self.nameLabel.text = model.full_name
        self.addresslabel.text = (model.final_install_address ).trimmingCharacters(in: .whitespaces)
        self.assignedByLabel.text = R.string.localizable.assignedBy(model.company )
        self.schedulerTimelabel.text = "Schedule Time: " + DateUtil().convertDateStrToDateStr(dateStr: model.scheduler_time, oldFormat: "MMM dd yyyy HH:mm:ss", newFormat: "dd/MM/yyyy hh:mm a")

        //设置底部按钮的view
        if model.allDone && model.status == PVDJobStatusName.installed.rawValue {
            allDoneImageView.isHidden = false
            barcodeBtn.isHidden = true
            checklistBtn.isHidden = true
            signatureBtn.isHidden = true
        }else{
            allDoneImageView.isHidden = true
            barcodeBtn.isHidden = false
            checklistBtn.isHidden = false
            
            signatureBtn.isHidden = model.solar_water_heater//swh不显示signature btn

            barcodeBtn.setData(.barcode, finishCnt: model.barcodeFinishCnt, plantCnt: model.barcodePlantCnt)
            checklistBtn.setData(.checklist, finishCnt: model.checklistFinishCnt, plantCnt: model.checklistPlantCnt)
            signatureBtn.setData(.signature, finishCnt: model.signatureFinishCnt, plantCnt: model.signaturePlantCnt)
        }
        self.powerLabel.text = ""
        self.powerLabel.isHidden = model.solar_water_heater ? true : false//pvd 才显示power label
        if model.solar_water_heater {//热水器
            
            self.jobTypeImageView.image = R.image.installation_list_jobtype_swh()
            if let type = HeaterInstallationTypeValue(rawValue: model.heater_installation_type) {
                if type == .None{//空，隐藏installation type
                    self.installationTypeLabel.isHidden = true
                }else{
                    switch type {
                    case .NewBuilding:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#346096")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.NewBuilding.rawValue.uppercased()
                    case .ReplacedElectricHeater:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#688F4E")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.ReplacedElectricHeater.rawValue.uppercased()
                    case .ReplaceGasWaterHeater:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#54ACB1")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.ReplaceGasWaterHeater.rawValue.uppercased()
                    case .ReplacedSolarWarterHeater:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#66A67B")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.ReplacedSolarWarterHeater.rawValue.uppercased()
                    case .FirstSolarWaterHeaterAtExistingBuilding:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#4D6EC3")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.FirstSolarWaterHeaterAtExistingBuilding.rawValue.uppercased()
                    case .Other:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#9FACBE")
                        self.installationTypeLabel.text = HeaterInstallationTypeName.Other.rawValue.uppercased()
                    default:
                        break
                    }
                    self.installationTypeLabel.isHidden = false
                }
            }
            if model.pick_up_required {//有就显示在installation type的下边
                self.pickUpRequired.isHidden = false
                self.pickUpRequired.text = R.string.localizable.pickUpRequired()
            }else{//没有就不显示
                self.pickUpRequired.isHidden = true
            }
        }else{//pvd
            self.jobTypeImageView.image = R.image.installation_list_jobtype_pvd()
            if let type = InstallationTypeValue(rawValue: model.installation_type) {
                if type == .none {
                    self.installationTypeLabel.isHidden = true
                }else{
                    switch type {
                    case .New:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#346096")
                        self.installationTypeLabel.text = InstallationTypeName.New.rawValue.uppercased()
                    case .Additional:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#688F4E")
                        self.installationTypeLabel.text = InstallationTypeName.Additional.rawValue.uppercased()
                    case .Replacement:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#66A67B")
                        self.installationTypeLabel.text = InstallationTypeName.Replacement.rawValue.uppercased()
                    case .Extension:
                        self.installationTypeLabel.backgroundColor = UIColor(hexStr: "#4D6EC3")
                        self.installationTypeLabel.text = InstallationTypeName.Extension.rawValue.uppercased()
                    default:
                        break
                    }
                }
                self.installationTypeLabel.isHidden = false
            }
            let ratedOutput = (model.rated_output == "" ? "0" :  model.rated_output)
            self.powerLabel.text = R.string.localizable.kW(ratedOutput)
            if model.pick_up_required {
                self.pickUpRequired.isHidden = false
                self.pickUpRequired.text = R.string.localizable.pickUpRequired()
            }else{
                self.pickUpRequired.isHidden = true
            }
        }
        self.dealThreeLabelLayout()
        self.jobStatusView.setData(model)
        
        
    }
    //处理installation type，power label，pick up required三个labal的布局
    private func dealThreeLabelLayout(){
        //1.installation type
        var installationTypeLabelWidth: CGFloat = 0
        if self.installationTypeLabel.isHidden == false{
            installationTypeLabelWidth = self.installationTypeLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))).width + Constant.InternalMargin
        }
        //2.power label
        var powerLabelWidth: CGFloat = 0
        if self.powerLabel.isHidden == false{
            powerLabelWidth = self.powerLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))).width + Constant.InternalMargin
        }
        //2.pick up required label
        var pickupRequiredLabelWidth: CGFloat = 0
        if self.pickUpRequired.isHidden == false{
            pickupRequiredLabelWidth = self.pickUpRequired.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))).width
        }
        let needMaxWidth = installationTypeLabelWidth + powerLabelWidth + pickupRequiredLabelWidth
        if needMaxWidth == 0 {
            installationTypeLabel.snp.remakeConstraints { make in
                make.edges.equalTo(assignedByLabel)
            }
            powerLabel.snp.remakeConstraints { make in
                make.edges.equalTo(installationTypeLabel)
            }
            pickUpRequired.snp.remakeConstraints { make in
                make.edges.equalTo(installationTypeLabel)
            }
        }else {
            //1.installation type
            installationTypeLabel.snp.remakeConstraints { make in
                make.left.equalTo(addresslabel)
                make.top.equalTo(assignedByLabel.snp.bottom).offset(12)
                make.height.width.greaterThanOrEqualTo(0)
            }
            //2.power
            if powerLabelWidth == 0 {
                powerLabel.snp.remakeConstraints { make in
                    make.edges.equalTo(installationTypeLabel)
                }
            }else{
                powerLabel.snp.remakeConstraints { make in
                    if installationTypeLabelWidth == 0{
                        make.left.equalTo(installationTypeLabel)
                    }else{
                        make.left.equalTo(installationTypeLabel.snp.right).offset(Constant.InternalMargin)
                    }
                    make.centerY.equalTo(installationTypeLabel)
                    make.width.height.greaterThanOrEqualTo(0)
                }
            }
            //3.pick up required
            if needMaxWidth <= (APPConfig.WidthForPortrait - (Constant.AllOutMargin + 12 + Constant.InternalMargin) * 2 ){//屏幕宽度足够显示三个label
                if pickupRequiredLabelWidth > 0{
                    pickUpRequired.snp.remakeConstraints { make in
                        make.left.equalTo(powerLabel.snp.right).offset(Constant.InternalMargin)
                        make.centerY.equalTo(powerLabel)
                        make.width.height.greaterThanOrEqualTo(0)
                    }
                }
            }else {//屏幕宽度不够显示三个label，pick up required需要换行显示
                if pickupRequiredLabelWidth > 0{
                    pickUpRequired.snp.remakeConstraints { make in
                        make.left.equalTo(installationTypeLabel)
                        make.top.equalTo(installationTypeLabel.snp.bottom).offset(12)
                        make.width.height.greaterThanOrEqualTo(0)
                    }
                }
            }
        }
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
class JobsListStatusView: View {
    var jobStatusLabel: ContentLabel!
    var progressView: UIProgressView!
    override func setUpView() {
        //job status
        //抗压缩，抗拉伸的能力最强
        jobStatusLabel = ContentLabel(R.font.interMedium(size: 13),hexStr: "#ED9A1DFF")
        jobStatusLabel.textAlignment = .left
        jobStatusLabel.setContentHuggingPriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        jobStatusLabel.setContentCompressionResistancePriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        self.addSubview(jobStatusLabel)
        jobStatusLabel.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //progress bar
        progressView = UIProgressView()
        progressView.drawCorner(byRoundingCorners: .allCorners, radii: 3)
        self.addSubview(progressView)
        progressView.snp.makeConstraints { (make) in
            make.left.equalTo(jobStatusLabel)
            make.top.equalTo(jobStatusLabel.snp.bottom).offset(4)
            make.height.equalTo(5)
            make.width.equalTo(jobStatusLabel)
            make.bottom.equalToSuperview()
        }
    }
    func setData(_ model: InstallationListModel){
        self.jobStatusLabel.text = model.status
        switch model.status {
            case PVDJobStatusName.scheduled.rawValue:
                self.jobStatusLabel.textColor = UIColor(hexStr: "#70798A")
                self.progressView.progressTintColor = UIColor(hexStr: "#70798A")
                self.progressView.backgroundColor = UIColor(hexStr: "#70798A33")
            case PVDJobStatusName.installing.rawValue:
                self.jobStatusLabel.textColor = UIColor(hexStr: "#ED9A1D")
                self.progressView.progressTintColor = UIColor(hexStr: "#ED9A1D")
                self.progressView.backgroundColor = UIColor(hexStr: "#ED9A1D33")
            case PVDJobStatusName.unqualified.rawValue:
                self.jobStatusLabel.textColor = UIColor(hexStr: "#DB4444")
                self.progressView.progressTintColor = UIColor(hexStr: "#DB4444")
                self.progressView.backgroundColor = UIColor(hexStr: "#DB4444")
            case PVDJobStatusName.installed.rawValue:
                self.jobStatusLabel.textColor = UIColor(hexStr: "#46B410")
                self.progressView.progressTintColor = UIColor(hexStr: "#46B410")
                self.progressView.backgroundColor = UIColor(hexStr: "#46B410")
            default:
                break

        }
        if model.completion_ratio >= 1 {
            self.progressView.setProgress(1, animated: true)
        }else{
            self.progressView.setProgress(Float(model.completion_ratio), animated: false)
        }
    }
}
